package com.ht.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.ht.constant.BusConstant;
import com.ht.module.sys.entity.SysUser;
import com.ht.module.sys.service.ISysUserService;
import com.ht.util.JsonResult;
import com.ht.util.JwtUtils;
import com.ht.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: ht
 * @ClassName: LocalAuthenticationSuccessHandler
 * @Author: hejialun
 * @Description: 登录成功处理
 * @Date: 2021/6/21 15:35
 */
@Component
public class LocalAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService iSysUserService;
    //过期时间
    @Value("${jwt.expireTime}")
    public long EXPIRE_TIME = 0;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //登录成功
        User user = (User) authentication.getPrincipal();
        SysUser sysUser=iSysUserService.getUserInfoByUsernameAll(user.getUsername());
        //吧用户信息存到token里面
        Map<String, Object> jwtMap=new HashMap<>();
        jwtMap.put("id",sysUser.getId());                   //设置用户id
        jwtMap.put("username",sysUser.getUsername());       //设置用户名
        jwtMap.put("password",sysUser.getPassword());       //设置用户密码
        String jwtToken = JwtUtils.sign(jwtMap);
        jwtMap.put("sysRoles",sysUser.getRoles());       //设置用户角色
        jwtMap.put("permissions",sysUser.getPermissions());       //设置用户角色
        jwtMap.put("sysMenus",sysUser.getSysMenus());       //设置用户角色

        //将用户信息存到redis
        redisUtil.set(BusConstant.USER_INFOS+jwtToken,jwtMap,EXPIRE_TIME);

        //吧用户信息返回给前端
        Map<String,Object> map=new HashMap<>();
        map.put("userInfo",sysUser);
        map.put("token",jwtToken);
        response.getWriter().print(JSON.toJSONString(JsonResult.success(map)));
    }

}